package com.fast.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fast.common.xss.SQLFilter;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Title：分页封装类
 * @author：ylc
 * @date：2018/7/13 14:03
 * @version：1.0
 **/
@Getter
public class PageQuery<T> extends LinkedHashMap<String, Object> {
    /**
     * mybatis-plus分页参数
     */
    private Page<T> page;
    /**
     * 当前页码
     */
    private int currPage = 1;
    /**
     * 每页条数
     */
    private int limit = 10;

    public PageQuery(Map<String, Object> params){
        this.putAll(params);

        //分页参数
        if(params.get("page") != null){
            currPage = Integer.parseInt((String)params.get("page"));
        }
        if(params.get("limit") != null){
            limit = Integer.parseInt((String)params.get("limit"));
        }

        this.put("offset", (currPage - 1) * limit);
        this.put("page", currPage);
        this.put("limit", limit);

        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderField = SQLFilter.sqlInject((String)params.get("orderField"));
        String order = SQLFilter.sqlInject((String)params.get("order"));
        this.put("orderField", orderField);
        this.put("order", order);

        //mybatis-plus分页
        this.page = new Page<>(currPage, limit);

        //排序
        if(StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)){
            if ("asc".equalsIgnoreCase(order)){
                page.setAscs(CommonUtil.humpToUnderline(orderField, true));
            }else {
                page.setDescs(CommonUtil.humpToUnderline(orderField, true));
            }
        }else {
            page.setDescs("create_time");
        }
    }
}
